package main

import (
	"io/ioutil"
	"log"
	"net/smtp"
	"strings"
	"time"

	"gitee.com/gricks/cron"
)

const (
	user = "astone@qq.com"
	from = "astone <" + user + ">"
	pswd = "xxxxxx"
	host = "smtp.exmail.qq.com"
	port = "25"
)

func BuildContent(content map[string]string, body string) string {
	var str string
	headers := []string{"To", "From", "Subject", "Content-Type"}
	for _, header := range headers {
		text, ok := content[header]
		if ok {
			str += header + ": " + text + "\r\n"
		}
	}
	str += "\r\n" + body
	return str
}

func SendMail(dest string, subject string, body string) error {
	content := make(map[string]string)
	content["To"] = dest
	content["From"] = from
	content["Subject"] = subject
	content["Content-Type"] = "text/html; charset=UTF-8"

	str := BuildContent(content, body)

	log.Println("Content: \n" + str)

	err := smtp.SendMail(
		host+":"+port,
		smtp.PlainAuth("", user, pswd, host),
		user,
		strings.Split(dest, ";"),
		[]byte(str))

	return err
}

func SendDailyMail() {
	for i := 0; i < 60; i++ {
		time.Sleep(10 * time.Second)

		destByte, err := ioutil.ReadFile("dest")
		if err != nil {
			log.Println(err)
			continue
		}
		dest := strings.Join(strings.Fields(string(destByte)), ";")

		subject := "subject"
		body := "body content"

		err = SendMail(string(dest), subject, body)
		if err != nil {
			log.Println("Error:", err)
			continue
		}

		log.Println("Send Success")
		return
	}
}

func main() {
	spec, err := ioutil.ReadFile("cron")
	if err != nil {
		panic(err)
	}

	c := cron.New()
	c.AddFunc(string(spec), SendDailyMail)
	c.Start()

	select {}
}
